const URL = 'https://www.oybtrip.com';

const app = getApp();

Page({
  data: {
    nickname: '账户名', //用户昵称
    avatar: '', //用户头像
    isLogin: false, //是否登录
    isAvatar: false, //是否获取头像
    isAvatarLoading: false, //获取头像loading
    isLoginLoading: false, //
    isPhoneLoading:false,
    mobile:'',
  },
  /**
   *
   * 调用JSAPI
   */
  async onJSAPIHandler() {
    this.setData({
      isAvatarLoading: true
    });
    if (!this.data.isAvatar) {
      try {
        const user = await this.getAvatarHandler();
        this.getPhoneNumber();
        app.globalData.nickName = user.nickName;
        app.globalData.avatar = user.avatar;
        this.setData({
          nickname: user.nickName,
          avatar: user.avatar,
          isAvatar: true,
          isAvatarLoading: false,
        });
      } catch (error) {
        console.error(error);
        this.toast(error.message);
        this.setData({
          nickname: '账户名',
          avatar: '',
          isAvatar: false,
          isAvatarLoading: false,
          mobile:'',
        });
      }
    } else {
      this.setData({
        nickname: '账户名',
        avatar: '',
        isAvatar: false,
        isAvatarLoading: false,
        mobile:'',
      });
    }
  },
  /**
   *  调用OPENAPI
   *
   */
  async onOpenAPIHandler() {
    if(this.data.mobile==''){
      my.alert({'content':"请先授权获取手机号!"});
      return;
    }
    this.setData({
      isLoginLoading: true
    });
    if (!this.data.isLogin) {
      try {
        const user = await this.getLoginUserHandler();
        this.getPhoneNumber();
        app.globalData.nickName = user.nickName;
        app.globalData.avatar = user.avatar;
        app.globalData.user_id = user.userId;
        app.globalData.isLogin = true;
        this.setData({
          nickname: user.nickName,
          avatar: user.avatar,
          isLogin: true,
          isLoginLoading: false
        });

        if(app.globalData.isLogin){
          my.reLaunch({
            url: '/pages/index/index'
          })

        }

      } catch (error) {
        console.error(error);
        this.toast(error.message);
        this.setData({
          nickname: '账户名',
          avatar: '',
          isLogin: false,
          isLoginLoading: false,
          mobile:'',
        });
      }
    } else {
      app.globalData.isLogin = false;
      this.setData({
        nickname: '账户名',
        avatar: '',
        isLogin: false,
        isLoginLoading: false,
        isAvatar: false,
        mobile:'',
      });
    }
  },
  async getLoginUserHandler() {
    return new Promise(async (resolve, reject) => {
      try {
        const auth = await this.getAuthCode(['auth_user']);
        const user = await this.getLoginUserInfo(auth.authCode);
        resolve(user);
      } catch (error) {
        console.log('error', error);
        reject(error);
      }
    });
  },
  getLoginUserInfo(authCode) {
    
    return new Promise((resolve, reject) => {
      my.httpRequest({
        url: `${URL}/app-api/chl/app/alipayUserInfo`,
        data: {
          authCode: authCode
        },
        headers:{"tenant-id":"1"},
        success: (res) => {
          if (!res.data.success) {
            reject({
              message: '登录失败',
              res
            });
          }
          resolve(res.data);
        },
        fail: (err) => {
          reject({
            message: '用户登录失败',
            err
          });
        }
      });
    });
  },
  getAvatarHandler() {
    return new Promise(async (resolve, reject) => {
      try {
        await this.getAuthCode('auth_user');
        const user = await this.getAuthUserInfo();
        resolve(user);
      } catch (error) {
        reject(error);
      }
    });
  },

  getAuthCode(scope) {
    return new Promise((resolve, reject) => {
      my.getAuthCode({
        scopes: scope,
        success: (auth) => {
          resolve(auth);
        },
        fail: (error) => {
          reject({
            message: '用户取消授权',
            error
          });
        }
      });
    });
  },
  getAuthUserInfo() {
    return new Promise((resolve, reject) => {
      my.getAuthUserInfo({
        success: (user) => {
          resolve(user);
        },
        fail: (error) => {
          reject({
            message: '获取用户头像失败',
            error
          });
        }
      });
    });
  },
  toast(message) {
    my.showToast({
      content: message,
      duration: 3000
    });
  },
  getPhoneNumber2() {
    this.getPhoneNumber();
   
  },

  getPhoneNumber(){
    var that=this;
    my.getPhoneNumber({
      scopes: 'phoneNumber',
      success: (res) => {
        let encryptedData = res.response;

        let params={
          encryptedData:res.response,
          sign:res.sign
        };

        my.request({
          url: `${URL}/app-api/chl/app/getPhone`,
          method: 'GET',
          data: params,
          headers:{"tenant-id":"1"},
          success: function (res) {
            let tel2 = res.data.mobile
            app.globalData.mobile = tel2;
            that.setData({
              mobile:tel2
            });
   
          },
        })
      },
      fail: (res) => {
        console.log(res);
      },
    });
    //my.alert({content:'用户id  -  '+app.globalData.user_id});
},
// 拒绝手机号
errorPhoneNumber(e){
  console.log('拒绝授权',e)

},
// 授权身份证号
getIDNumber(){
  var that=this;
	my.getIDNumber({
    scopes: 'IDNumber',
		success: async (res) => {
			console.log('授权成功',res)
      let encryptedData = res.response;

        let params={
          encryptedData:res.response,
          sign:res.sign
        };
      
        my.request({
          url: `${URL}/app-api/chl/app/getIdNumber`,
          method: 'GET',
          data: params,
          headers:{"tenant-id":"1"},
          success: function (res) {
            my.alert({content:res.data});
            let idStr = res.data.IDNumber
            app.globalData.IDNumber = idStr;
            that.setData({
              IDNumber:idStr
            });
   
          },
        })

		},
		fail: (err) => {
			console.log('授权失败',err)
		}
	})
},
// 拒绝身份证号
errorIDNumber(e){
	console.log('拒绝授权',e)
}
});
